<template>
  <div>
    <el-card class="card" style="max-width: 75vw">
      <div class="card-header">
        <el-icon :size="30">
          <Promotion />
        </el-icon>
        <span class="title"> 消息中心 </span>
        <el-button id="sendNotice" type="primary" @click="sendMessageButton">发送消息</el-button>
      </div>
      <div class="noticeTable">
        <el-table class="listTable" :data="noticeListData" :border=true style="width: 100%" :max-height="'70vh'">
          <el-table-column prop="messageTitle" label="通知名称" :width="tableWidth[0]" :align="'center'" />
          <el-table-column prop="targetClubName" label="所属社团" :width="tableWidth[1]" :align="'center'" />
          <el-table-column prop="sourcePersonName" label="发送人" :width="tableWidth[2]" :align="'center'" />
          <el-table-column prop="createTime" label="发出时间" :width="tableWidth[3]" :align="'center'" />
          <el-table-column prop="operation" label="操作" :width="tableWidth[4]" :align="'center'">
            <template #default="scope">
              <el-button id="buttonNoticeShow" @click="handleInDetails(scope.row)">查看详情</el-button>
              <el-button  type="primary" :disabled="scope.row.isRead==1"  @click="readOne(scope.row)">标为已读</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>

  <el-dialog v-model="DialogVisible" 
  :title=DialogTitle 
  width="700" align-center>
  {{ content }}
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="DialogVisible = false">关闭详情</el-button>
      </div>
    </template>
  </el-dialog>


  <el-dialog v-model="createDialogVisible" title="创建消息" width="700">
    <div>
      <el-form :model="newNotice" style="max-width: 500px;">
        <el-form-item label="消息标题">
          <el-input v-model="newNotice.messageTitle" maxlength="20" show-word-limit/>
        </el-form-item>
        <el-form-item label="消息类型">
          <el-radio-group v-model="newNotice.sendType">
            <el-radio value="0">发送给个人</el-radio>
            <el-radio v-if="permission==2" value="1">发送给社团</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="newNotice.sendType != 0 && newNotice.sendType !=1" label="目标" />
        <el-form-item v-if="newNotice.sendType == 1" label="目标社团">
          <el-select v-model="newNotice.targetClubId" placeholder="--请选择--" style="width: 240px">
            <el-option v-for="clubSelect in clubList" :key="clubSelect.value" :label="clubSelect.label" :value="clubSelect.value" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="newNotice.sendType == 0" label="目标人员">
            <el-input v-if="newNotice.sendType == 0" v-model="targetPersonName" @change="onPersonChange" style="width: 240px" placeholder="输入姓名关键词" />
            <el-button v-if="newNotice.sendType == 0" @click="lookupPerson">查询</el-button>
        </el-form-item>
        <el-form-item label="消息内容">
          <el-input v-model="newNotice.messageContent" type="textarea" maxlength="500" show-word-limit placeholder="请输入消息内容"/>
        </el-form-item>
      </el-form>
    </div>
    <div class="dialog-footer">
      <el-button @click="createDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="sendMessage">发送</el-button>
    </div>
  </el-dialog>
  <el-drawer direction="ltr" v-model="drawer" title="查询结果如下" >
    <span>
      <el-select @change="onPersonChange"
      v-model="newNotice.targetPersonId"
      placeholder="--请选择人员--"
      size="large"
      style="width: 300px"
      >
      <el-option
       v-for="item in options" 
       :key="item.id"
       :label="item.id+`&nbsp&nbsp`+item.userName"
       :value="item.id"
      />
    </el-select>
    </span>
  </el-drawer>
</template>

<script setup>
import { ref, onMounted, reactive, onUnmounted } from 'vue';
import api from '@/api';
import showMessageTip from '@/utils/showMessage';
import userStore from '@/stores/store';
import debounce from '@/utils/debounce';

const DialogVisible = ref(false)
let DialogTitle = ref('');
let content=ref('');
const createDialogVisible = ref(false);
const tableWidth = ref([]);
const tableWidthRatio = ref([0.32, 0.17, 0.14, 0.15, 0.22]);
const targetPersonName = ref('');
const noticeListData = ref([])
const newNotice = reactive({
  messageTitle:'',
  messageContent:'',
  targetClubId:null,
  targetPersonId:-1,
  sendType:-1     //0 私发 1 群发
})

const clubList = ref([]);
const options = ref([]);
const drawer=ref(false);
const permission =ref(userStore().getPermission);
const targetClubId=ref(null);
var debounceSetColumnSize = null;

const sendMessageButton = async()=>{
  createDialogVisible.value = true;
  const clubListResult = await api.getManagedClub();
  if(clubListResult[0]==0){
    if(clubListResult[1].data.code==1){
      clubList.value=[];
      const tempClubList = clubListResult[1].data.data;
      for(let i=0;i<tempClubList.length;i++){
        if(tempClubList[i].clubState == 2)  continue;
        const tempNameId = ref({
          label:tempClubList[i].clubName,
          value:tempClubList[i].clubId
        })
        clubList.value.push(tempNameId.value);
    }
    }
  }
  else{
    showMessageTip('网络请求失败','error');
  }
}
onMounted(() => {
  const width = document.querySelector('.card').getBoundingClientRect().width-40;
  tableWidth.value[4] = width;
  for (let i = 0; i < 4; i++) {
    tableWidth.value[i] = tableWidthRatio.value[i] * width;
    tableWidth.value[4] -= tableWidth.value[i];
  }
})
onMounted( () => {
  debounceSetColumnSize = debounce(setColumnSize, 300);
  window.addEventListener('resize', debounceSetColumnSize);
})
onUnmounted(() => {
  window.removeEventListener('resize', debounceSetColumnSize);
  debounceSetColumnSize.cancel();
});
const setColumnSize = () => {
  const width = document.querySelector('.card').getBoundingClientRect().width-40;
  tableWidth.value[4]=width;
  for(let i = 0; i<4 ;i++){
    tableWidth.value[i] = tableWidthRatio.value[i]*width;
    tableWidth.value[4] -= tableWidth.value[i];
  }
}

const handleInDetails= async(rowdata)=>{  //查看详情功能
  const currentMessageID = reactive({ messageId:rowdata.messageId});
  DialogTitle.value =rowdata.messageTitle;
  const result = await api.getSingleMsg(currentMessageID);
  if(result[0]==0){
    const data =result[1].data;
    if(data.code == 1){
      content=data.data;
      DialogVisible.value = true;
    }
    else{
    showMessageTip('消息获取失败','error');
    }
  }
  else{
    showMessageTip('网络请求失败','error');
  }
}
const readOne= async (rowData)=>{   //已读功能
  
const setReadresult=await api.setMsgReaded({ messageId:rowData.messageId});
  if(setReadresult[0]==0){
    const data = setReadresult[1].data;
    if(data.code==1){
      showMessageTip('已读了一条消息', 'success');
      rowData.isRead=1;
    }
    else{
      showMessageTip('操作失败','error');
    }
  }
  else{
    showMessageTip('网络请求失败','error');
  }
}
const lookupPerson = async ()=>{
    const searchResult = await api.getSbIdName({userName:targetPersonName.value});
    if(searchResult[0]==0){
        const data = searchResult[1].data;
        if(data.code==1){
            showMessageTip('查询成功', 'success');
            drawer.value=true;
            const researchList = data.data;
            options.value = researchList;
            return;
        }
        else{
          showMessageTip('查询失败', 'error');
        }
    }
    else{
        showMessageTip('网络请求失败', 'error');
        return;
    }
  
};
const sendMessage = async ()=>{
  if(newNotice.messageTitle == '' || newNotice.messageContent == '' || !(newNotice.sendType==0 || newNotice.sendType==1) 
     || ( newNotice.targetClubId == null && newNotice.targetPersonId == -1 )){
    showMessageTip('请填写完整信息','warning');
    return;
  }
  const sendResult = await api.sendMessage(newNotice);
  if(sendResult[0]==0){
    const data = sendResult[1].data;
    if(data.code == 1){
        showMessageTip('发送成功', 'success');
        createDialogVisible.value=false;
        newNotice.messageTitle = '';
        newNotice.messageContent = '';
        newNotice.sendType = -1;
        newNotice.targetClubId = null;
        newNotice.targetPersonId = -1;
        targetPersonName.value = '';
        return;
    }
    else{
        showMessageTip('发送失败', 'error');
        return;
    }
  }
  else{
    showMessageTip('网络请求失败', 'error');
    return;
  }
};
const onPersonChange = () => {
  const temp = ref();
  temp.value = options.value.find(item =>item["id"]===newNotice.targetPersonId);
  if(temp.value != null) {
    targetPersonName.value = temp.value.userName;
  }
}

onMounted(async () => {
  const msgResult = await api.getMessageList();
  if (msgResult[0] == 0) {
    let data = msgResult[1].data;
    const tempNotice= ref([]); //储存已读的消息
    if (data.code == 1) {
      for(let i = 0; i < data.data.length; i++){
        data.data[i].createTime = data.data[i].createTime.replace('T', ' ').substring(0, data.data[i].createTime.length - 3);
        if(data.data[i].sendType == 0) {
          data.data[i].targetClubName = "私发";
        }
        else if(data.data[i].sendType == 1 && data.data[i].targetClubName == null)  {
          data.data[i].targetClubName = "社团已解散";
        }
        if(data.data[i].isRead==0){
          noticeListData.value.push(data.data[i]);
        }
        else{
          tempNotice.value.push(data.data[i]);
        }
      }
      noticeListData.value = noticeListData.value.concat(tempNotice.value);
      return;
    }
    else {
      showMessageTip('查询失败', 'error');
      return;
    }
  }
  else {
    showMessageTip('网络请求失败', 'error');
    return;
  }
})
</script>


<style scoped>
.title {
  font-weight: bold;
  font-size: 32px;
  font-family: "黑体";
}

.listTable {
  margin-top: 12px;
}

.card-header{
  display: flex;
  padding-left: 10px;
}

:deep(.listTable .el-table__header-wrapper th) {
  background-color: #549DFD;
  color: #fff;
  font-family: 'Microsoft YaHei';
}

#buttonRead {
  border: none;
  background-color: #009900;
  color: #FFF;
}

#buttonNoticeShow {
  border: #549DFD 1.5px solid;
  color: #549DFD;
}

#sendNotice{
  margin-left: auto;
  margin-right: 10px;
  background-color: #00a31b;
  border: none;
}
.dialog-footer{
  display: flex;
  justify-content: flex-end;
}
</style>